package com.sm.appbase.example.net;


import androidx.annotation.NonNull;

import com.google.gson.GsonBuilder;
import com.sm.appbase.net.gsondefaultadapter.DoubleDefaultAdapter;
import com.sm.appbase.net.gsondefaultadapter.FloatDefaultAdapter;
import com.sm.appbase.net.gsondefaultadapter.IntegerDefaultAdapter;
import com.sm.appbase.net.gsondefaultadapter.LongDefaultAdapter;
import com.sm.appbase.net.gsondefaultadapter.StringNullAdapter;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionSpec;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.TlsVersion;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class DemoRetrofitClient {
    private static volatile DemoRetrofitClient instance;

    //<editor-folder desc="各个模块API">
    private AccountAPIService accountApiService;

    //</editor-folder >
    private DemoRetrofitClient() {
    }

    public static DemoRetrofitClient getInstance() {
        if (instance == null) {
            synchronized (DemoRetrofitClient.class) {
                if (instance == null) {
                    instance = new DemoRetrofitClient();
                }
            }
        }
        return instance;
    }

    //<editor-folder desc="各个模块API">

    /**
     * API
     */
    public AccountAPIService getAccountApi() {
        if (accountApiService == null) {
            accountApiService = getRetrofitClient().create(AccountAPIService.class);
        }
        return accountApiService;
    }


    //</editor-folder  >


//<editor-folder desc="基础配置">

    /**
     * 设置Header
     *
     * @return
     */
    private Interceptor getHeaderInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder()
                        //添加Token
                        .header("user","");
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        };

    }

    /**
     * 设置拦截器
     *
     * @return
     */
    private Interceptor getInterceptor() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        //显示日志
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return interceptor;
    }

    private Retrofit getUploadFileRetrofitClient() {
        OkHttpClient okHttpClient;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder()
                        //添加Token
                        .header("user", "")
                        .header("content-type", "multipart/form-data");
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });
        builder.addInterceptor(getInterceptor());
        //超时时间
        builder.connectTimeout(15, TimeUnit.SECONDS);//15S连接超时
        builder.readTimeout(20, TimeUnit.SECONDS);//20s读取超时
        builder.writeTimeout(20, TimeUnit.SECONDS);//20s写入超时

        builder.hostnameVerifier(new AllowAllHostnameVerifier());

        //错误重连
        builder.retryOnConnectionFailure(true);
        ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
                .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
                .allEnabledCipherSuites()
                .build();//解决在Android5.0版本以下https无法访问
        ConnectionSpec spec1 = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT).build();//兼容http接口
        builder.connectionSpecs(Arrays.asList(spec, spec1));
//        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
//        builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
        okHttpClient = builder.build();

        return new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl("HOST")
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .registerTypeAdapter(Integer.class, new IntegerDefaultAdapter())
                        .registerTypeAdapter(int.class, new IntegerDefaultAdapter())
                        .registerTypeAdapter(Double.class, new DoubleDefaultAdapter())
                        .registerTypeAdapter(double.class, new DoubleDefaultAdapter())
                        .registerTypeAdapter(Long.class, new LongDefaultAdapter())
                        .registerTypeAdapter(long.class, new LongDefaultAdapter())
                        .registerTypeAdapter(Float.class, new FloatDefaultAdapter())
                        .registerTypeAdapter(float.class, new FloatDefaultAdapter())
                        .registerTypeAdapter(String.class, new StringNullAdapter())
                        .create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    private Retrofit getRetrofitClient() {
        ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
                .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
                .allEnabledCipherSuites()
                .build();//解决在Android5.0版本以下https无法访问
        ConnectionSpec spec1 = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT).build();//兼容http接口
        OkHttpClient client = new OkHttpClient().newBuilder()
                //设置Header
                .addInterceptor(getHeaderInterceptor())
                //设置拦截器
                .addInterceptor(getInterceptor())
                .callTimeout(25, TimeUnit.SECONDS)
                .connectTimeout(25, TimeUnit.SECONDS)
                .writeTimeout(25,TimeUnit.SECONDS)
                .readTimeout(25,TimeUnit.SECONDS)
                .connectionSpecs(Arrays.asList(spec, spec1))
                .build();
        return new Retrofit.Builder()
                .client(client)
                .baseUrl("HOSTT")
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .registerTypeAdapter(Integer.class, new IntegerDefaultAdapter())
                        .registerTypeAdapter(int.class, new IntegerDefaultAdapter())
                        .registerTypeAdapter(Double.class, new DoubleDefaultAdapter())
                        .registerTypeAdapter(double.class, new DoubleDefaultAdapter())
                        .registerTypeAdapter(Long.class, new LongDefaultAdapter())
                        .registerTypeAdapter(long.class, new LongDefaultAdapter())
                        .registerTypeAdapter(Float.class, new FloatDefaultAdapter())
                        .registerTypeAdapter(float.class, new FloatDefaultAdapter())
                        .registerTypeAdapter(String.class, new StringNullAdapter())
                        .create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }
    //</editor-folder desc="基础配置">

}
